/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.mongodb.repository.listener;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.stereotype.Component;

import com.foreveross.bsl.common.utils.factory.InstanceFactory;
import com.foreveross.bsl.common.utils.factory.InstanceSpringProvider;
import com.foreveross.bsl.mongodb.repository.MongodbConfig;
import com.foreveross.bsl.mongodb.repository.source.MongodbSources;


/**
 * @description 因为@Component后，当spring容器初始化时自动促发事件：初始化mongodb基础设施
 *
 * @author rening
 * @version v1.0
 *
 * @2013-7-18
 *
 */
@Component
public class MongodbSourcesListener implements ApplicationListener<ApplicationEvent> {

	/* (non-Javadoc)
	 * @see org.springframework.context.ApplicationListener#onApplicationEvent(org.springframework.context.ApplicationEvent)
	 */
	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if(event instanceof ContextRefreshedEvent) { // 初始化事件
			ApplicationContext context = ((ContextRefreshedEvent) event).getApplicationContext();
			if(context.getParent() != null){
				context = context.getParent();
			}
			InstanceFactory.setInstanceProvider(new InstanceSpringProvider(context));
			MongoDbFactory factory = InstanceFactory.getContextInstance(MongoDbFactory.class);
			MongodbConfig config = InstanceFactory.getContextInstance(MongodbConfig.class);
			MongodbSources.init(config, factory);
		}
	}

}
